package cn.itcast.search.service.impl;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.hmall.dto.common.PageDTO;
import cn.itcast.hmall.dto.common.ResultDTO;
import cn.itcast.hmall.dto.search.SearchReqDTO;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.item.ItemDoc;
import cn.itcast.search.service.SearchService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author oldwine
 * @date 2022/6/21
 * @Version 1.0
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;

    @Override
    public void importItemData(List<Item> itemList) throws IOException {

        // 2. 将数据批量的添加到 es索引库中
        BulkRequest bulkRequest = new BulkRequest();
        for (Item item : itemList) {
            // 3. for循环遍历 要批量插入的酒店列表，每一个酒店数据 都封装成一个IndexRequest对象
            IndexRequest request = new IndexRequest("item");
            request.id(item.getId() + ""); // 设置文档id
            ItemDoc itemDoc = new ItemDoc(item);
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON); // 设置文档内容
            // 4. 将 添加文档的请求  加入到 批处理请求中
            bulkRequest.add(request);
        }
        // 5. 执行批处理请求
        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }

    @Override
    public List<String> getSuggestions(String key) {
        try {
            // 1. 创建请求
            SearchRequest request = new SearchRequest("item");
            // 2. 添加suggest搜索条件
            SearchSourceBuilder source = request.source();
            // 3. 搜索索引库中 suggestion字段中  以 key为前缀的所有词条   (只显示前10个词条)
            source.suggest(
                    new SuggestBuilder()
                            .addSuggestion(
                                    "mySuggestion",  // 自定义的查询名称
                                    SuggestBuilders.completionSuggestion("suggestion")
                                            .prefix(key)  // 匹配前缀为key的词条
                                            .skipDuplicates(true) // 去除重复的词条
                                            .size(10) // 保留10条
                            )
            );
            // 4. 执行请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 查询suggest结果
            Suggest suggest = response.getSuggest();
            // 根据自定义的名称 找到具体的suggest结果
            CompletionSuggestion suggestion = suggest.getSuggestion("mySuggestion");
            // 获取options 遍历options
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> suggestionList = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                suggestionList.add(option.getText().toString());
            }
            return suggestionList;
            // 5. 解析响应结果
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("自动补全查询失败");
        }
    }

    /**
     * 过滤项聚合功能
     *
     * @param params 查询参数对象
     * @return 返回查询结果
     */
    @Override
    public Map<String, List<String>> getFilters(SearchReqDTO params) {
        try {
            // 1. 创建搜索请求
            SearchRequest request = new SearchRequest("item");
            SearchSourceBuilder source = request.source();
            // 2. 设置query查询条件
            buildBasicQuery(params, source);
            // 3. 设置size = 0
            source.size(0);
            // 4. 设置 聚合请求条件   brand分组  city分组  starName分组
            buildAggregations(source);
            // 5. 执行聚合搜索请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 6. 解析响应内容 获取聚合结果 brand分组  city分组  starName分组
            // 6.1 获取总的聚合结果
            Aggregations aggregations = response.getAggregations();
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");

            // 7. 将结果封装成 Map<String,List<String>>
            Map<String, List<String>> map = new HashMap<>();
            map.put("brand", brandList);
            map.put("category", categoryList);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("聚合查询失败");
        }
    }

    /**
     * 基本所搜功能实现
     *
     * @param params 请求参数封装
     * @return
     */
    @Override
    public PageDTO<ItemDoc> search(SearchReqDTO params) {
        try {
            // 1. 创建搜索请求
            SearchRequest request = new SearchRequest("item");
            // 1.1 构建查询条件
            SearchSourceBuilder source = request.source();
            buildBasicQuery(params, source);

            //设置排序 设置按照销量降序 如果销量一致 按照评论降序
            source.sort("sold", SortOrder.DESC);
            source.sort("commentCount", SortOrder.DESC);
            source.sort("price", SortOrder.ASC);

            // 设置分页
            source.from((params.getPage() - 1) * params.getSize());
            source.size(params.getSize());

            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("name");
            highlightBuilder.preTags("<em>");
            highlightBuilder.postTags("</em>");
            highlightBuilder.requireFieldMatch(false);
            source.highlighter(highlightBuilder);
            // 2. 执行搜索请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //3.解析响应结果
            SearchHits hits = response.getHits();
            PageDTO<ItemDoc> pageResult = new PageDTO<>();
            // 设置查询结果数量
            pageResult.setTotal(hits.getTotalHits().value);
            List<ItemDoc> list = new ArrayList<>();
            // 遍历文档列表
            for (SearchHit hit : hits) {
                // 获取每个文档的source内容(文档json字符串)  ==> 转为 HotelDoc文档java对象
                ItemDoc itemDoc = JSON.parseObject(hit.getSourceAsString(), ItemDoc.class);
                // 处理高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    //将name字段高亮处理
                    HighlightField highlightField = highlightFields.get("name");
                    //将高亮片段拼接完整字符串
                    String highlightStr = StringUtils.join(highlightField.getFragments());
                    // 将高亮结果替换name字段
                    itemDoc.setName(highlightStr);
                }
                list.add(itemDoc);
            }
            pageResult.setList(list);
            return pageResult;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("es搜索出错了");
        }
    }

    /**
     * 根据商品id添加商品信息
     *
     * @param id 商品id
     */
    @Override
    public void insertById(Long id) {
        try {
            //1.根据id查询商品数据 远程调用 商品微服务根据id查询商品数据的接口 查询数据
            Item item = itemClient.getItemById(id);
            //2.将商品对象转换成文档对象
            ItemDoc itemDoc = new ItemDoc(item);
            //3.创建请求对象
            IndexRequest request = new IndexRequest("item").id(item.getId().toString());
            request.source(JSON.toJSONString(itemDoc),XContentType.JSON);
            //4.发送请求
            client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据id删除商品信息
     * @param id 商品id
     */
    @Override
    public void deleteById(Long id) {
        try {
            //1.创建请求对象
            DeleteRequest request = new DeleteRequest("item", id.toString());
            //2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * @param aggregations 聚合结果对象
     * @param aggName      自定义聚合名称
     * @return
     */
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 6.2 获取指定聚合结果
        Terms aggResult = aggregations.get(aggName);
        // 6.3 获取结果中的分组信息 buckets
        List<? extends Terms.Bucket> buckets = aggResult.getBuckets();
        // 6.4 遍历分组  得到分组内容
        List<String> resultList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 获取每个分组的key 加入到集合
            resultList.add(bucket.getKeyAsString());
        }
        // 将集合返回
        return resultList;
    }

    /**
     * 构建聚合条件
     *
     * @param source
     */
    private void buildAggregations(SearchSourceBuilder source) {
        source.aggregation(
                AggregationBuilders.terms("brandAgg")
                        .field("brand")
                        .size(20)
        );
        source.aggregation(
                AggregationBuilders.terms("categoryAgg")
                        .field("category")
                        .size(20)
        );
    }

    /**
     * 构建query查询条件
     *
     * @param params
     * @param source
     */
    private void buildBasicQuery(SearchReqDTO params, SearchSourceBuilder source) {
        // 构建布尔条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.isBlank(params.getKey())) {
            // 如果 key为空 就查询全部
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            // 如果 key不为空  使用match  查询 all字段
            boolQuery.must(QueryBuilders.matchQuery("all", params.getKey()));
        }
        // 如果分类不为空  使用term查询 category字段
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }
        // 如果品牌不为空  使用term查询 brand字段
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        // 如果价格不为空  使用range查询 price字段
        Double maxPrice = params.getMaxPrice();
        Double minPrice = params.getMinPrice();
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lt(maxPrice));
        }
        // 算分函数条件
        FunctionScoreQueryBuilder functionScoreQueryBuilder =
                QueryBuilders.functionScoreQuery(
                        // 原始的查询条件
                        boolQuery,
                        // 算分函数 数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 算分函数
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 筛选条件 （哪些文档需要重新计算得分）
                                        QueryBuilders.termQuery("isAD", true),
                                        // 计算得分的方法  weight直接给一个常量分值
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        }
                        // 加权模式: (算分 和 原始得分 如何计算 ) 默认相乘
                ).boostMode(CombineFunction.MULTIPLY);
        source.query(functionScoreQueryBuilder);
    }
}
